#include "musicplayer.h"
#include "ui_musicplayer.h"

#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <QJsonObject>
#include <QJsonArray>
#include <QFileDialog>
#include <QMouseEvent>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QDebug>

MusicPlayer::MusicPlayer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MusicPlayer)
    , currentIndex(-1)
{
    ui->setupUi(this);

    initUi();
    initSqlite();
    initMusicList();
    initPlayer();

    connectSignalAndSlots();
}

MusicPlayer::~MusicPlayer()
{
    delete ui;
}

void MusicPlayer::initUi()
{
    // 设置窗口图标
    this->setWindowIcon(QIcon(":/images/icon.png"));

    // 添加系统托盘
    QSystemTrayIcon* trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/images/icon.png"));
    trayIcon->show();
    // 给托盘添加菜单
    QMenu* trayMenu = new QMenu();
    trayMenu->addAction("显示", this, &QWidget::showNormal);
    trayMenu->addAction("退出", this, &MusicPlayer::onMusicPlayerQuit);
    trayIcon->setContextMenu(trayMenu);
    // 关联信号槽，单击或双击激活系统托盘图标时，显示程序
    connect(trayIcon, &QSystemTrayIcon::activated, this, &QWidget::showNormal);

    // 设置无边框窗口，同时窗口无标题栏
    this->setWindowFlag(Qt::FramelessWindowHint);

    // 设置窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground);

    // 给窗口设置阴影效果
    QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setOffset(0, 0);  // 设置阴影偏移：无偏移
    shadowEffect->setColor("#000000");  // 设置阴影颜色：黑色
    shadowEffect->setBlurRadius(20);  // 设置阴影的模糊半径
    this->setGraphicsEffect(shadowEffect);  // 把阴影设置到当前窗口上

    // 设置BtForm图标和文本
    ui->rec->setIconAndText(":/images/rec.png", "推荐", 0);
    ui->radio->setIconAndText(":/images/radio.png", "电台", 1);
    ui->music->setIconAndText(":/images/music.png", "音乐馆", 2);
    ui->like->setIconAndText(":/images/like.png", "我喜欢", 3);
    ui->local->setIconAndText(":/images/local.png", "本地下载", 4);
    ui->recent->setIconAndText(":/images/recent.png", "最近播放", 5);

    // 程序刚启动时，默认显示“推荐”页
    ui->local->setStyleSheet("#btStyle{ border-radius: 10px; background-color: rgb(223, 225, 228); }");
    ui->stackedWidget->setCurrentIndex(4);

    // 初始化推荐页内容
    srand(time(nullptr));
    ui->recMusicBox->initRecBoxUi(randomPicture(), 1);
    ui->supplyMusicBox->initRecBoxUi(randomPicture(), 2);

    // 设置CommonPage的信息
//    ui->likePage->setPageType(PageType::LIKE_PAGE);
    ui->likePage->setCommonPageTitle("我喜欢");
//    ui->localPage->setPageType(PageType::LOCAL_PAGE);
    ui->localPage->setCommonPageTitle("本地下载");
    ui->localPage->showAddLocalBtn();
//    ui->recentPage->setPageType(PageType::HISTORY_PAGE);
    ui->recentPage->setCommonPageTitle("最近播放");

    // 实例化音量调节窗口
    volumeTool = new VolumeTool(this);

    // 实例化歌词窗口对象
    lrcPage = new LrcPage(ui->background);
    lrcPage->hide();
    lrcPageIsShow = false;
    lrcPage->stackUnder(ui->controlBox);

    // 播放控制区按钮图标设定
//    ui->play->setIcon(QIcon(":/images/play.png"));
    ui->play->setStyleSheet("#play { background-image: url(:/images/play.png); }");
    ui->playMode->setStyleSheet("#playMode { background-image: url(:/images/order_play.png); } #playMode:hover { background-image: url(:/images/order_play-green.png); }");

    ui->head->installEventFilter(this);
    ui->skin->installEventFilter(this);
    ui->min->installEventFilter(this);
    ui->max->installEventFilter(this);
    ui->quit->installEventFilter(this);
}

void MusicPlayer::initSqlite()
{
    // 1. 进行数据库驱动加载
    sqlite = QSqlDatabase::addDatabase("QSQLITE");

    // 2. 设置数据库名称
    sqlite.setDatabaseName("MusicPlayer.db");

    // 3. 打开数据库
    if (!sqlite.open())
    {
        QMessageBox::critical(this, "MusicPlayer", "数据库打开失败！！！");
        return;
    }
//    qDebug() << "数据库连接成功";

    // 4. 创建表
    QString sql("CREATE TABLE IF NOT EXISTS MusicInfo(\
                id INTEGER PRIMARY KEY AUTOINCREMENT,\
                musicId varchar(50) UNIQUE,\
                musicName varchar(50),\
                musicSinger varchar(50),\
                albumName varchar(50),\
                musicUrl varchar(256),\
                duration BIGINT,\
                isLike INTEGER,\
                isHistory INTEGER,\
                coverImage BLOB);");

    QSqlQuery query;
    if (!query.exec(sql))
    {
        QMessageBox::critical(this, "MusicPlayer", "初始化错误！！！");
        return;
    }
    qDebug() << "MusicInfo表创建成功";

    sql = "CREATE TABLE IF NOT EXISTS LikePageMusicInfo( musicUrl varchar(256) );";
    if (!query.exec(sql))
    {
        QMessageBox::critical(this, "MusicPlayer", "初始化错误！！！");
        return;
    }
    qDebug() << "LikePageMusicInfo表创建成功";

    sql = "CREATE TABLE IF NOT EXISTS LocalPageMusicInfo( musicUrl varchar(256) );";
    if (!query.exec(sql))
    {
        QMessageBox::critical(this, "MusicPlayer", "初始化错误！！！");
        return;
    }
    qDebug() << "LocalPageMusicInfo表创建成功";

    sql = "CREATE TABLE IF NOT EXISTS RecentPageMusicInfo( musicUrl varchar(256) );";
    if (!query.exec(sql))
    {
        QMessageBox::critical(this, "MusicPlayer", "初始化错误！！！");
        return;
    }
    qDebug() << "RecentPageMusicInfo表创建成功";
}

void MusicPlayer::initMusicList()
{
    // 读取数据库
    musicList.readFromDB();

    // 恢复界面歌曲列表
    ui->likePage->setPageType(PageType::LIKE_PAGE);
    ui->likePage->readFromDB(musicList);
    ui->localPage->setPageType(PageType::LOCAL_PAGE);
    ui->localPage->readFromDB(musicList);
    ui->recentPage->setPageType(PageType::HISTORY_PAGE);
    ui->recentPage->readFromDB(musicList);
}

void MusicPlayer::initPlayer()
{
    // 初始化媒体播放相关类对象
    player = new QMediaPlayer(this);
    playlist = new QMediaPlaylist(this);
    prevPlayPage = nullptr;
    currentPlayPage =  nullptr;

    // 设置默认的播放模式
    playlist->setPlaybackMode(QMediaPlaylist::Sequential);
    ui->playMode->setToolTip("顺序播放");

    // 将播放列表设置到播放器中
    player->setPlaylist(playlist);

    // 设置默认的音量大小，默认设置成20%
    player->setVolume(20);

    // 关联播放器状态改变的信号槽
    connect(player, &QMediaPlayer::stateChanged, this, &MusicPlayer::onPlayerStateChanged);
    // 关联player中播放源发生变化的信号槽
//    connect(player, &QMediaPlayer::durationChanged, this, &MusicPlayer::onDurationChanged);
    // 关联player中播放时长发生变化的信号槽
    connect(player, &QMediaPlayer::positionChanged, this, &MusicPlayer::onPositionChanged);
    // 关联播放模式状态改变的信号槽
    connect(playlist, &QMediaPlaylist::playbackModeChanged, this, &MusicPlayer::onPlaybackModeChanged);
    // 关联playlist中播放源发生变化的信号槽
    connect(playlist, &QMediaPlaylist::currentIndexChanged, this, &MusicPlayer::onCurrentIndexChanged);
    // 关联进度条发生变化的信号槽
    connect(ui->progressBar, &MusicSlider::setMusicSliderPosition, this, &MusicPlayer::onMusicSliderChanged);
    // 关联元数据发生改变的信号槽
    connect(player, &QMediaObject::metaDataAvailableChanged, this, &MusicPlayer::onMetaDataAvailableChanged);
}

void MusicPlayer::connectSignalAndSlots()
{
    // 关联BtForm的信号和处理该信号的槽函数
    connect(ui->rec, &BtForm::btClicked, this, &MusicPlayer::onBtFormClicked);
    connect(ui->radio, &BtForm::btClicked, this, &MusicPlayer::onBtFormClicked);
    connect(ui->music, &BtForm::btClicked, this, &MusicPlayer::onBtFormClicked);
    connect(ui->like, &BtForm::btClicked, this, &MusicPlayer::onBtFormClicked);
    connect(ui->local, &BtForm::btClicked, this, &MusicPlayer::onBtFormClicked);
    connect(ui->recent, &BtForm::btClicked, this, &MusicPlayer::onBtFormClicked);

    // 关联点击添加本地音乐的按钮的信号和槽函数
    connect(ui->localPage, &CommonPage::addLocalMusic, this, &MusicPlayer::addLocalMusic);

    // 关联点击“我喜欢”按钮的信号和槽函数
    connect(ui->likePage, &CommonPage::updateLikeMusic, this, &MusicPlayer::updateLikeMusicAndPage);
    connect(ui->localPage, &CommonPage::updateLikeMusic, this, &MusicPlayer::updateLikeMusicAndPage);
    connect(ui->recentPage, &CommonPage::updateLikeMusic, this, &MusicPlayer::updateLikeMusicAndPage);

    // 关联点击“播放全部”按钮或者双击某首歌的信号和槽函数
    connect(ui->likePage, &CommonPage::playMusicByPageAndIndex, this, &MusicPlayer::onPlayMusicByPageAndIndex);
    connect(ui->localPage, &CommonPage::playMusicByPageAndIndex, this, &MusicPlayer::onPlayMusicByPageAndIndex);
    connect(ui->recentPage, &CommonPage::playMusicByPageAndIndex, this, &MusicPlayer::onPlayMusicByPageAndIndex);

    // 处理音量
    connect(volumeTool, &VolumeTool::setMusicMuted, this, &MusicPlayer::setPlayerMuted);
    connect(volumeTool, &VolumeTool::setMusicVolume, this, &MusicPlayer::setPlayerVolume);

    // 关闭歌词页面的信号槽
    connect(lrcPage, &LrcPage::lrcPageMoveDown, this, &MusicPlayer::on_lrcPageBtn_clicked);
}

QJsonArray MusicPlayer::randomPicture()
{
    // 推荐文本 + 推荐图片路径
    QVector<QString> vecImageName;
    vecImageName << "01.jpg" << "02.jpg" << "03.jpg" << "04.jpg" << "05.jpg"
                 << "06.jpg" << "07.jpg" << "08.jpg" << "09.jpg" << "10.jpg"
                 << "11.jpg" << "12.jpg" << "13.jpg" << "14.jpg" << "15.jpg"
                 << "16.jpg" << "17.jpg" << "18.jpg" << "19.jpg" << "20.jpg"
                 << "21.jpg" << "22.jpg" << "23.jpg" << "24.jpg" << "25.jpg"
                 << "26.jpg" << "27.jpg" << "28.jpg" << "29.jpg" << "30.jpg"
                 << "31.jpg" << "32.jpg" << "33.jpg" << "34.jpg" << "35.jpg"
                 << "36.jpg" << "37.jpg" << "38.jpg" << "39.jpg" << "40.jpg";

    // 打乱顺序
    std::random_shuffle(vecImageName.begin(), vecImageName.end());

    // 01.jpg
    // path: ":/images/rec/" + vecImageName[i]
    // text: "推荐-001"
    // path和text是一一对应的关系，可以用<k,v>来管理
    QJsonArray objArray;
    for (int i = 0; i < vecImageName.size(); ++i)
    {
        QJsonObject obj;
        obj.insert("path", ":/images/rec/" + vecImageName[i]);
        QString strText = QString("推荐-%1").arg(i + 1, 3, 10, QChar('0'));
        obj.insert("text", strText);

        objArray.append(obj);
    }

    return objArray;
}

void MusicPlayer::onMusicPlayerQuit()
{
    qDebug() << "退出程序";
    // 歌曲信息写入数据库
    musicList.writeToDB();
    ui->likePage->writeToDB();
    ui->localPage->writeToDB();
    ui->recentPage->writeToDB();

    // 断开与SQLite的连接
    sqlite.close();

    // 关闭窗口
    close();
}

void MusicPlayer::on_quit_clicked()
{
    // 隐藏窗口
    hide();
}

void MusicPlayer::onBtFormClicked(int pageId)
{
    // 清除之前选中的BtForm按钮的背景颜色和动画效果
    // 获取所有的BtForm按钮，除pageId外，其余全部清除
    QList<BtForm*> btFormList = this->findChildren<BtForm*>();
    for (auto btForm : btFormList)
    {
        if (btForm->getPageId() != pageId)
        {
            btForm->clearBackground();
        }
    }

    // 切换页面
    ui->stackedWidget->setCurrentIndex(pageId);
}

//void MusicPlayer::mousePressEvent(QMouseEvent *event)
//{
//    // 拦截鼠标左键单击事件
//    if (Qt::LeftButton == event->button())
//    {
//        // event->globalPos()：⿏标按下事件发⽣时，光标相对于屏幕左上⻆位置
//        dragPosition = event->globalPos() - geometry().topLeft();
//        return;
//    }

//    QWidget::mousePressEvent(event);
//}

//void MusicPlayer::mouseMoveEvent(QMouseEvent *event)
//{
//    if (Qt::LeftButton == event->buttons())
//    {
//        this->move(event->globalPos() - dragPosition);
//        return;
//    }

//    QWidget::mouseMoveEvent(event);
//}

bool MusicPlayer::eventFilter(QObject *watched, QEvent *event)
{
    if (ui->skin == watched || ui->min == watched || ui->max == watched || ui->quit == watched)
    {
        if (event->type() == QEvent::MouseButtonPress)
        {
            isDrag = false;
        }
    }
    else if (ui->head == watched)
    {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        if (event->type() == QEvent::MouseButtonPress)
        {
            if (Qt::LeftButton == mouseEvent->button())
            {
                isDrag = true;
                // event->globalPos()：⿏标按下事件发⽣时，光标相对于屏幕左上⻆位置
                dragPosition = mouseEvent->globalPos() - geometry().topLeft();
            }
        }
        else if (event->type() == QEvent::MouseMove)
        {
            if (Qt::LeftButton == mouseEvent->buttons() && isDrag)
            {
                this->move(mouseEvent->globalPos() - dragPosition);
            }
        }
        return true;
    }
    return QObject::eventFilter(watched, event);
}

void MusicPlayer::on_volume_clicked()
{
    // 将ui->volume控件的左上角坐标，转换为基于屏幕左上角的坐标
    QPoint point = ui->volume->mapToGlobal(QPoint(0, 0));

    // 根据ui->volume控件的位置，计算弹窗显示的位置
    QPoint volumeToolLeftTop = point - QPoint(volumeTool->width() / 2 - ui->volume->width() / 2, volumeTool->height());

    // 移动volumeTool
    volumeTool->move(volumeToolLeftTop);

    // 显示窗口
    volumeTool->show();
}

void MusicPlayer::addLocalMusic()
{
    QFileDialog fileDialog(this);
    fileDialog.setWindowTitle("添加本地下载音乐");

    // 设置文件对话框默认的打开路径
//    QDir dir(QDir::currentPath());
//    dir.cdUp();
//    dir.cdUp();
//    QString projectPath = dir.path();
//    projectPath += "/music";
//    fileDialog.setDirectory(projectPath);

    // 设置为一次打开多个文件
    fileDialog.setFileMode(QFileDialog::ExistingFiles);

    // 通过文件后缀设置过滤器
//    fileDialog.setNameFilter("代码文件(*.h *.c *.hpp *.cpp)");
//    fileDialog.setNameFilter("图片文件(*.png *.jpg *.bmp)");

    // 通过文件的MIME类型来过滤
    QStringList mimeTypeFilters;
    mimeTypeFilters << "application/octet-stream";  // All(*)
    fileDialog.setMimeTypeFilters(mimeTypeFilters);

    if (QDialog::Accepted == fileDialog.exec())
    {
        // 获取被选中的文件，fileUrls内部存放的是刚刚选中的文件的url路径
        QList<QUrl> fileUrls = fileDialog.selectedUrls();

        // 将所有音乐添加到音乐列表中，MusicList
        QList<QUrl> validfileUrls = musicList.addMusicsByUrl(fileUrls);

        // 将歌曲信息更新到CommonPage页面的listWidget中
        ui->localPage->addMusics(validfileUrls, musicList, currentPlayPage, playlist);

        // 将localPage中的歌曲添加到媒体播放列表中
//        ui->localPage->addMusicToPlaylist(playlist);
//        currentPlayPage = ui->localPage;
    }
}

void MusicPlayer::updateLikeMusicAndPage(bool isLike, iterator it)
{
    // 修改状态
    it->setIsLike(isLike);

    // 本地和最近播放界面只需修改图标
    ui->localPage->setItemIsLike(it);
    ui->recentPage->setItemIsLike(it);

    // 如果正在播放的就是这首歌，播放区域的图标也需要改变样式
    if (currentPlayPage)
    {
        QUrl url = currentPlayPage->getMusicUrlByIndex(currentIndex);
        if (it->getMusicUrl() == url)
        {
            setAddLikeIcon(isLike);
        }
    }

    // 我喜欢界面需要添加或移除歌曲
    if (isLike) ui->likePage->addMusic(it, musicList, currentPlayPage, playlist);
    else ui->likePage->removeMusic(it, musicList, currentPlayPage, playlist);
}

// 播放控制区
// 播放和暂停
void MusicPlayer::on_play_clicked()
{
    if (QMediaPlayer::PlayingState == player->state())
    {
        // 播放中点击，应该暂停
        player->pause();
//        ui->play->setStyleSheet("#play { background-image: url(:/images/play.png); }");
    }
    else if (QMediaPlayer::PausedState == player->state())
    {
        // 暂停状态下点击按钮，应该继续播放
        player->play();
//        ui->play->setStyleSheet("#play { background-image: url(:/images/play_on.png); }");
    }
    else if (QMediaPlayer::StoppedState == player->state())
    {
        // 刚开始运行，默认为停止状态，此时点击按钮，直接播放音乐列表第0首歌
        onPlayMusicByPageAndIndex(ui->localPage, 0);
//        playlist->setCurrentIndex(0);
//        player->play();
//        ui->play->setStyleSheet("#play { background-image: url(:/images/play_on.png); }");
    }
    else
    {
        qDebug() << player->errorString();
    }
}

void MusicPlayer::onPlayerStateChanged(QMediaPlayer::State state)
{
    if (QMediaPlayer::PlayingState == state)
    {
        ui->play->setStyleSheet("#play { background-image: url(:/images/play_on.png); }");
        currentPlayPage->setStyleByIndex(currentIndex, true, true);  // 播放时显示动画
    }
    else
    {
        ui->play->setStyleSheet("#play { background-image: url(:/images/play.png); }");
        currentPlayPage->setStyleByIndex(currentIndex, false, true);  // 暂停时隐藏动画
    }
}

void MusicPlayer::on_playUp_clicked()
{
    if (playlist->currentIndex() == 0 && QMediaPlaylist::Sequential == playlist->playbackMode())
    {
        QMessageBox::information(this, "温馨提示", "前面已无可播放歌曲");
        return;
    }
    playlist->previous();
    player->play();
}

void MusicPlayer::on_playDown_clicked()
{
    if (playlist->currentIndex() == playlist->mediaCount() - 1 && QMediaPlaylist::Sequential == playlist->playbackMode())
    {
        QMessageBox::information(this, "温馨提示", "后面已无可播放歌曲");
        return;
    }
    playlist->next();
    player->play();
}

void MusicPlayer::on_playMode_clicked()
{
    // 1.根据当前播放模式，切换到下一个播放模式
    // 2.设置ToolTip提示
    // 3.状态发生改变时，修改按钮上的图标
    // 顺序播放 --> 列表循环 --> 单曲循环 --> 随机播放
    if (QMediaPlaylist::Sequential == playlist->playbackMode())
    {
        playlist->setPlaybackMode(QMediaPlaylist::Loop);
        ui->playMode->setToolTip("列表循环");
    }
    else if (QMediaPlaylist::Loop == playlist->playbackMode())
    {
        playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
        ui->playMode->setToolTip("单曲循环");
    }
    else if (QMediaPlaylist::CurrentItemInLoop == playlist->playbackMode())
    {
        playlist->setPlaybackMode(QMediaPlaylist::Random);
        ui->playMode->setToolTip("随机播放");
    }
    else if (QMediaPlaylist::Random == playlist->playbackMode())
    {
        playlist->setPlaybackMode(QMediaPlaylist::Sequential);
        ui->playMode->setToolTip("顺序播放");
    }
    else
    {
        // 正常不会出现这种情况
        playlist->setPlaybackMode(QMediaPlaylist::Sequential);
        ui->playMode->setToolTip("顺序播放");
    }
}

void MusicPlayer::onPlaybackModeChanged(QMediaPlaylist::PlaybackMode mode)
{
    if (QMediaPlaylist::Sequential == mode)
    {
        ui->playMode->setStyleSheet("#playMode { background-image: url(:/images/order_play.png); } #playMode:hover { background-image: url(:/images/order_play-green.png); }");
    }
    else if (QMediaPlaylist::Loop == mode)
    {
        ui->playMode->setStyleSheet("#playMode { background-image: url(:/images/list_play.png); } #playMode:hover { background-image: url(:/images/list_play-green.png); }");
    }
    else if (QMediaPlaylist::CurrentItemInLoop == mode)
    {
        ui->playMode->setStyleSheet("#playMode { background-image: url(:/images/single_play.png); } #playMode:hover { background-image: url(:/images/single_play-green.png); }");
    }
    else if (QMediaPlaylist::Random == mode)
    {
        ui->playMode->setStyleSheet("#playMode { background-image: url(:/images/shuffle_play.png); } #playMode:hover { background-image: url(:/images/shuffle_play-green.png); }");
    }
    else
    {
        // 正常不会出现
        ui->playMode->setStyleSheet("#playMode { background-image: url(:/images/order_play.png); } #playMode:hover { background-image: url(:/images/order_play-green.png); }");
    }
}

void MusicPlayer::onPlayMusicByPageAndIndex(CommonPage *page, int index)
{
    if (page != currentPlayPage)
    {
        // 清空之前playlist中的歌曲
        playlist->clear();
//        qDebug() << "清空播放列表";
        // 添加当前要播放的page页面中的所有歌曲
        page->addMusicToPlaylist(playlist);
        currentPlayPage = page;
    }
    // 设置从第index首歌开始播放
    playlist->setCurrentIndex(index);
    // 播放
    player->play();
}

void MusicPlayer::onCurrentIndexChanged(int index)
{
    // 去掉上一首歌的动画和样式，设置当前播放歌曲的动画和样式
    if (prevPlayPage) prevPlayPage->setStyleByIndex(currentIndex, false, false);
    currentPlayPage->setStyleByIndex(index, true, false);

    // 本首歌赋值给上首歌
    prevPlayPage = currentPlayPage;
    currentIndex = index;

    // 播放列表中的歌曲顺序和CommonPage页面中的歌曲顺序是相同的
    QUrl musicUrl = currentPlayPage->getMusicUrlByIndex(index);
    auto it = musicList.findMusicByMusicUrl(musicUrl);

    QString musicName("未知歌曲");
    QString musicSinger("未知歌手");
    QString musicAlbum("未知专辑");
    QString lrcPath;
    bool isLike = false;
    QPixmap coverImage(":/images/default_album_image.png");
    if (it != musicList.end())
    {
        // 设置总时长文本
        totalTime = it->getDuration();
        ui->totalDuration->setText(QString("%1:%2").arg(totalTime / 1000 / 60, 2, 10, QChar('0')).arg(totalTime / 1000 % 60, 2, 10, QChar('0')));

        // 更新当前播放歌曲信息
        musicName = it->getMusicName();
        musicSinger = it->getMusicSinger();
        coverImage = it->getCoverImage();
        musicAlbum = it->getMusicAlbum();
        lrcPath = it->getLrcFilePath();  // 获取lrc文件的路径
        isLike = it->getIsLike();

        // 添加进最近播放列表中
        it->setIsHistory(true);
        ui->recentPage->addMusicToRecentPage(it);
        if (currentPlayPage != ui->recentPage)
        {
            ui->recentPage->removeMusic(it, musicList, currentPlayPage, playlist);
            ui->recentPage->addMusic(it, musicList, currentPlayPage, playlist);
        }
    }
    ui->musicName->setText(musicName);
    ui->musicSinger->setText(musicSinger);
    ui->musicCover->setPixmap(coverImage);
    ui->musicCover->setScaledContents(true);
    setAddLikeIcon(isLike);

    // 解析歌曲的lrc歌词
    lrcPage->setLrcName(musicName);
    lrcPage->setLrcSinger("歌手：" + musicSinger);
    lrcPage->setLrcAlbum("专辑：" + musicAlbum);
    lrcPage->parseLrcFile(lrcPath);
}

void MusicPlayer::setPlayerMuted(bool isMuted)
{
    player->setMuted(isMuted);
    setVolumeImage(isMuted);
}

void MusicPlayer::setPlayerVolume(int volume)
{
    player->setVolume(volume);
    setVolumeImage(volume == 0);
}

void MusicPlayer::setVolumeImage(bool isMuted)
{
    if (isMuted)
    {
        ui->volume->setStyleSheet("#volume { background-image: url(:/images/silent.png); } #volume:hover { background-image: url(:/images/silent-green.png) }");
    }
    else
    {
        ui->volume->setStyleSheet("#volume { background-image: url(:/images/volumn.png); } #volume:hover { background-image: url(:/images/volumn-green.png) }");
    }
}

//void MusicPlayer::onDurationChanged(qint64 duration)
//{
//    // 这种方式获取到的总时长偏大，不准确，元数据的方式获取的是准确的
//    (void)duration;
//    // 设置总时长文本
//    totalTime = duration;
//    ui->totalDuration->setText(QString("%1:%2").arg(duration / 1000 / 60, 2, 10, QChar('0')).arg(duration / 1000 % 60, 2, 10, QChar('0')));
//}

void MusicPlayer::onPositionChanged(qint64 position)
{
    // 更新进度条的位置
    ui->progressBar->setStep((float)position / totalTime);

    // 更新当前播放时长文本
    ui->currentDuration->setText(QString("%1:%2").arg(position / 1000 / 60, 2, 10, QChar('0')).arg(position / 1000 % 60, 2, 10, QChar('0')));

    // 在歌词界面同步显示歌词
    if (currentIndex >= 0)
    {
        lrcPage->showLrcWordLine(position);
    }
}

void MusicPlayer::onMusicSliderChanged(float ratio)
{
    // 根据进度条进度，更新当前播放时间
    qint64 position = totalTime * ratio;
    player->setPosition(position);
    ui->currentDuration->setText(QString("%1:%2").arg(position / 1000 / 60, 2, 10, QChar('0')).arg(position / 1000 % 60, 2, 10, QChar('0')));
}

void MusicPlayer::onMetaDataAvailableChanged(bool available)
{
    (void)available;
}

void MusicPlayer::on_lrcPageBtn_clicked()
{
    if (lrcPageAnimationUp == nullptr)
    {
        // 设置歌词界面的尺寸和位置
        lrcPage->setGeometry(0, 0, ui->background->width(), ui->background->height());
        // 初始化歌词页面上移动画
        lrcPageAnimationUp = new QPropertyAnimation(lrcPage, "geometry", this);
        lrcPageAnimationUp->setDuration(300);
        lrcPageAnimationUp->setStartValue(QRect(0, lrcPage->height(), lrcPage->width(), lrcPage->height()));
        lrcPageAnimationUp->setEndValue(QRect(0, 0, lrcPage->width(), lrcPage->height()));
        // 初始化歌词页面上移动画
        lrcPageAnimationDown = new QPropertyAnimation(lrcPage, "geometry", this);
        lrcPageAnimationDown->setDuration(300);
        lrcPageAnimationDown->setStartValue(QRect(0, 0, lrcPage->width(), lrcPage->height()));
        lrcPageAnimationDown->setEndValue(QRect(0, lrcPage->height(), lrcPage->width(), lrcPage->height()));

        // 显示歌词页面
        lrcPage->show();
    }

    if (lrcPageIsShow)
    {
        lrcPageAnimationDown->start();  // 开启动画
        lrcPageIsShow = false;

//        // 关联信号槽，收到信号时隐藏窗口
//        connect(lrcPageAnimationDown, &QPropertyAnimation::finished, this, [=](){
//            lrcPage->hide();
//        });
    }
    else
    {
        lrcPageAnimationUp->start();  // 开启动画
        lrcPageIsShow = true;
    }
}

void MusicPlayer::on_skin_clicked()
{
    // 换肤
    QMessageBox::information(this, "温馨提示", "换肤功能暂不支持");
}

void MusicPlayer::on_min_clicked()
{
    // 最小化
    this->showMinimized();
}

void MusicPlayer::on_max_clicked()
{
    if (isMaximized)
    {
        showNormal();
        ui->max->setStyleSheet("#max { background-image: url(:/images/max.png); } #max:hover{ background-image: url(:/images/max-green.png); }");
        isMaximized = false;
    }
    else
    {
        showMaximized();
        ui->max->setStyleSheet("#max { background-image: url(:/images/max2.png); } #max:hover{ background-image: url(:/images/max2-green.png); }");
        isMaximized = true;
    }
}

void MusicPlayer::on_addLike_clicked()
{
    QUrl url = currentPlayPage->getMusicUrlByIndex(currentIndex);
    iterator it = musicList.findMusicByMusicUrl(url);
    updateLikeMusicAndPage(!it->getIsLike(), it);
}

void MusicPlayer::setAddLikeIcon(bool isLike)
{
    if (isLike)
    {
        ui->addLike->setStyleSheet("#addLike { background-image: url(:/images/like_solid.png); } #addLike:hover { background-image: url(:/images/like_solid-hover.png); }");
    }
    else
    {
        ui->addLike->setStyleSheet("#addLike { background-image: url(:/images/like_hollow.png); } #addLike:hover { background-image: url(:/images/like_hollow-hover.png); }");
    }
}
